package org.ncibi.cytoscape.metscape.task;

import org.ncibi.cytoscape.metscape.data.ConceptData;
import org.ncibi.cytoscape.metscape.data.GeneData;
import org.ncibi.cytoscape.metscape.data.Organism;

import cytoscape.Cytoscape;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;

public class LRpathTask implements Task {

	private TaskMonitor taskMonitor;
	private boolean interrupted = false;
	private GeneData geneData;
	private Organism organism;
	private ConceptData conceptData;
	private String pValueColumn;
	private String foldChangeColumn;

	public static ConceptData runUsingGeneData(GeneData geneData, Organism organism, 
			String pValueColumn, String foldChangeColumn) {
		LRpathTask task = new LRpathTask(geneData, organism, pValueColumn, foldChangeColumn);
		return configureAndRunTask(task);
	}

	private LRpathTask(GeneData geneData, Organism organism, String pValueColumn, String foldChangeColumn) {
		this.geneData = geneData;
		this.organism = organism;
		this.pValueColumn = pValueColumn;
		this.foldChangeColumn = foldChangeColumn;
	}

	private static ConceptData configureAndRunTask(LRpathTask task) {
		// Configure JTask Dialog Pop-Up Box
		JTaskConfig jTaskConfig = new JTaskConfig();
		jTaskConfig.setOwner(Cytoscape.getDesktop());
		jTaskConfig.displayCancelButton(true);
		jTaskConfig.displayStatus(true);

		// Execute Task in New Thread; pops open JTask Dialog Box.
		if(TaskManager.executeTask(task, jTaskConfig))
			return task.conceptData;
		else return null;
	}

	public void setTaskMonitor(TaskMonitor monitor)
			throws IllegalThreadStateException {
		taskMonitor = monitor;
	}

	public void halt() {
		interrupted = true;
	}

	public String getTitle() {
		return "Running LRpath";
	}

	public void run() {
		try {
			interrupted = false;
			taskMonitor.setPercentCompleted(-1);
			taskMonitor.setStatus("Initializing...");

			if (geneData != null) {
					taskMonitor.setStatus("Generating concept data using LRpath...");
					conceptData = ConceptData.generateUsingLRpath(geneData, organism, pValueColumn, foldChangeColumn);
					if (conceptData == null
							|| interrupted) 
						throw new Exception("Generating concept data failed");
					else if(conceptData.isEmpty())
						throw new Exception("We were unable to find any significant concepts for the gene data and columns " +
								"that you selected.  Please make sure the correct data, organism, and columns are selected, and try again.");
			
			}

			taskMonitor.setStatus("Complete");
			taskMonitor.setPercentCompleted(100);
		}

		catch (Throwable t) {
			if (!interrupted)
				taskMonitor.setException(t,
						"An error occurred while loading data for the MetScape session: "
								+ t.getLocalizedMessage());
		}
	}
}
